package org.se.scut.pinterest.mina.handler;

import java.util.Date;
import java.util.List;
import org.apache.mina.core.session.IoSession;
import org.se.scut.hibernate.dao.model.PictureType;
import org.se.scut.hibernate.dao.service.PictureTypeImp;
import org.se.scut.hibernate.dao.service.iface.IPictureTypeService;
import org.se.scut.pinterest.mina.codec.msg.AllPictureTypeMessage;
import org.se.scut.pinterest.mina.codec.msg.AllPictureTypeResultMessage;
import org.se.scut.pinterest.mina.codec.msg.AllPictureTypeResultMessageItem;
import org.se.scut.pinterest.mina.codec.msg.Message;
import org.se.scut.pinterest.mina.handler.observer.IMessageObserver;
import org.se.scut.pinterest.mina.handler.observer.MessageOperatorType;
import org.se.scut.pinterest.mina.utils.FormateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AllPictureTypeHandler implements IMessageObserver {

	private static final Logger LOGGER = LoggerFactory.getLogger(AllPictureTypeHandler.class);
	private final IPictureTypeService typeService = new PictureTypeImp();
	
	@Override
	public void onMessageChange(IoSession session, Message msg,
			MessageOperatorType type) {
		LOGGER.info(msg.getSymbol());
		String serverLastDate = typeService.getLastModifiedDate();
		String clientLastDate = ((AllPictureTypeMessage)msg).getLastModifiedDate();
		if (isChanged(serverLastDate, clientLastDate)) {
			session.write(getAllMsg());
		LOGGER.info("size: " + getAllMsg().getItems().size());
		}else {
			session.write(new AllPictureTypeResultMessage());
		}
	}
	
	private boolean isChanged(String serverLastDate, String clientLastDate){
		Date serverDate = FormateUtils.dateFormate(serverLastDate);
		Date clientDate = FormateUtils.dateFormate(clientLastDate);
		boolean isChanged = serverDate.before(clientDate);
		return isChanged;
	}
	
	
	private AllPictureTypeResultMessage getAllMsg(){
		AllPictureTypeResultMessage msg = new AllPictureTypeResultMessage();
		List<AllPictureTypeResultMessageItem> items = msg.getItems();
		List<PictureType> types = typeService.getAllPictureTypes();
		for (PictureType pictureType : types) {
			AllPictureTypeResultMessageItem item = new AllPictureTypeResultMessageItem();
			item.setId(pictureType.getId());
			item.setLastModifiedDate(FormateUtils.formateDate(pictureType.getLastModifiedTime()));
			item.setTypeName(pictureType.getTypeName());
			items.add(item);
		}
		return msg;
	}

}
